#include <iostream>
#include <string>

#include <cstring>

#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>

#include <arpa/inet.h>
#include <netinet/in.h>

#include "Common.hpp"

// ./TcpClient_tcp server_ip server_port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Usage:./TcpClient_tcp server_ip server_port" << std::endl;
    }

    std::string server_ip = argv[1];
    int server_port = std::stoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cout << "create socket failed" << std::endl;
        return SOCKET_ERR;
    }

    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(server_port);
    server_addr.sin_addr.s_addr = inet_addr(server_ip.c_str());

    // client 由操作系统动态 bind，客户端在 connect 的时候 会自动 bind
    int n = ::connect(sockfd, CONV(&server_addr), sizeof(server_addr));
    if (n < 0)
    {
        std::cout << "connect failed " << std::endl;
        return CONNECT_ERR;
    }
    // echo client
    std::string msg;
    while (true)
    {
        std::cout << "Enter message: ";
        std::getline(std::cin, msg);

        n = ::write(sockfd, msg.c_str(), msg.size());
        char buffer[1024];
        if (n > 0)
        {
            int m = ::read(sockfd, buffer, sizeof(buffer));
            if (m > 0)
            {
                buffer[m] = 0;
                std::cout << buffer << std::endl;
            }
            else
                break;
        }
        else
            break;
    }

    ::close(sockfd);
    return 0;
}